<style>
    .red{color: blue}
</style>
<?php
$username = trim($_POST['username']); //使用POST全局数组获取前端表单提交的数据
$pw = trim($_POST['pw']);
$cpw = trim($_POST['cpw']);
$sex = $_POST['sex'];
$fav = @implode(',',$_POST['fav']);
$email = trim($_POST['email']);
//进行后端数据验证
if(!strlen($username) || !strlen($pw)){
    echo "<script>alert('用户名和密码都必须要填写');history.back();</script>";
    exit;
}
else{
    if(!preg_match('/^[a-zA-Z0-9]{3,10}$/',$username)){
        echo "<script>alert('用户名只能是大小字字符和数字构成，长度为3-10个字符');history.back();</script>";
        exit;
    }
}
if($pw <> $cpw){
    echo "<script>alert('密码和确认密码必须相同');history.back();</script>";
    exit;
}
else{
    if(!preg_match('/^[a-zA-Z0-9_*]{6,10}$/',$pw)){
        echo "<script>alert('密码只能是大小字字符和数字，以及*、_构成，长度为6-10个字符');history.back();</script>";
        exit;
    }
}
if(!empty($email)){
    if(!preg_match('/^[a-zA-Z0-9_\-]+@([a-zA-z0-9]+\.)+(com|cn|net|org)$/',$email)){
        echo "<script>alert('邮箱格式不正确');history.back();</script>";
        exit;
    }
}
include_once 'conn.php';
//第3步，设置查询语句
//在写入数据库之前，要先查询当前用户名是否已经存在
//如果已经存在，则提示此用户名不可用。
$sql = "select id from userinfo where username = '$username'";
$result = mysqli_query($conn,$sql);
//判断$result里是否有记录
if(mysqli_num_rows($result)){
    echo "<script>alert('当前用户名已经使用过了');history.back();</script>";
    exit;
}
if($sex == NULL){
    $sql = "insert into userinfo (username,pw,fav,email) values ('$username','" . md5($pw) . "','$fav','$email')";
}
else{
    $sql = "insert into userinfo (username,pw,sex,fav,email) values ('$username','" . md5($pw) . "','$sex','$fav','$email')";
}
//第4步，执行查询语句
$result = mysqli_query($conn,$sql);
/*echo $sql . "<br>";  //程序调试之第1招：打印sql语句
echo mysqli_error($conn);//程序调试之第2招：打印mysqli错误信息
exit;*/
//执行成功，返回一个记录集，执行失败，返回false
if($result){
    echo "<script>alert('数据插入成功');history.back();</script>";
}
else{
    echo "<script>alert('数据插入失败');history.back();</script>";
}
?>